package com.msxt.controller;

import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.MatchRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.msxt.annotation.IgnoreAuth;
import com.msxt.dto.ConfigEntity;
import com.msxt.result.R;
import com.msxt.service.CommonService;
import com.msxt.service.ConfigService;
import com.msxt.utils.BaiduUtil;
import com.msxt.utils.FileUtil;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 通用接口
 */
@RestController
public class CommonController {
	@Autowired
	private CommonService commonService;

	private static AipFace client = null;

	@Autowired
	private ConfigService configService;

	/**
	 * 获取table表中的column列表(联动接口)
	 */
	@IgnoreAuth
	@RequestMapping("/option/{tableName}/{columnName}")
	public R getOption(@PathVariable("tableName") String tableName,
					   @PathVariable("columnName") String columnName,
					   @RequestParam(required = false) String conditionColumn,
					   @RequestParam(required = false) String conditionValue,
					   String level, String parent) {
		Map<String, Object> params = new HashMap<>();
		params.put("table", tableName);
		params.put("column", columnName);
		if(StringUtils.isNotBlank(level)) {
			params.put("level", level);
		}
		if(StringUtils.isNotBlank(parent)) {
			params.put("parent", parent);
		}
		if(StringUtils.isNotBlank(conditionColumn)) {
			params.put("conditionColumn", conditionColumn);
		}
		if(StringUtils.isNotBlank(conditionValue)) {
			params.put("conditionValue", conditionValue);
		}
		List<String> data = commonService.getOption(params);
		return R.ok().put("data", data);
	}

	/**
	 * 根据table中的column获取单条记录
	 */
	@IgnoreAuth
	@RequestMapping("/follow/{tableName}/{columnName}")
	public R getFollowByOption(@PathVariable("tableName") String tableName,
							   @PathVariable("columnName") String columnName,
							   @RequestParam String columnValue) {
		Map<String, Object> params = new HashMap<>();
		params.put("table", tableName);
		params.put("column", columnName);
		params.put("columnValue", columnValue);
		Map<String, Object> result = commonService.getFollowByOption(params);
		return R.ok().put("data", result);
	}

	/**
	 * 修改table表的sfsh状态
	 */
	@RequestMapping("/sh/{tableName}")
	public R sh(@PathVariable("tableName") String tableName,
				@RequestBody Map<String, Object> map) {
		map.put("table", tableName);
		commonService.sh(map);
		return R.ok();
	}

	/**
	 * 获取需要提醒的记录数
	 */
	@IgnoreAuth
	@RequestMapping("/remind/{tableName}/{columnName}/{type}")
	public R remindCount(@PathVariable("tableName") String tableName,
						 @PathVariable("columnName") String columnName,
						 @PathVariable("type") String type,
						 @RequestParam Map<String, Object> map) {
		map.put("table", tableName);
		map.put("column", columnName);
		map.put("type", type);

		if("2".equals(type)) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar c = Calendar.getInstance();
			Date remindStartDate = null;
			Date remindEndDate = null;
			if(map.get("remindstart") != null) {
				Integer remindStart = Integer.parseInt(map.get("remindstart").toString());
				c.setTime(new Date());
				c.add(Calendar.DAY_OF_MONTH, remindStart);
				remindStartDate = c.getTime();
				map.put("remindstart", sdf.format(remindStartDate));
			}
			if(map.get("remindend") != null) {
				Integer remindEnd = Integer.parseInt(map.get("remindend").toString());
				c.setTime(new Date());
				c.add(Calendar.DAY_OF_MONTH, remindEnd);
				remindEndDate = c.getTime();
				map.put("remindend", sdf.format(remindEndDate));
			}
		}

		long  count= commonService.remindCount(map);
		return R.ok().put("count", count);
	}

	/**
	 * 单列求和
	 */
	@IgnoreAuth
	@RequestMapping("/cal/{tableName}/{columnName}")
	public R cal(@PathVariable("tableName") String tableName,
				 @PathVariable("columnName") String columnName) {
		Map<String, Object> params = new HashMap<>();
		params.put("table", tableName);
		params.put("column", columnName);
		Map<String, Object> result = commonService.selectCal(params);
		return R.ok().put("data", result);
	}

	/**
	 * 分组统计
	 */
	@IgnoreAuth
	@RequestMapping("/group/{tableName}/{columnName}")
	public R group(@PathVariable("tableName") String tableName,
				   @PathVariable("columnName") String columnName) {
		Map<String, Object> params = new HashMap<>();
		params.put("table", tableName);
		params.put("column", columnName);
		List<Map<String, Object>> result = commonService.selectGroup(params);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		for(Map<String, Object> m : result) {
			for(String k : m.keySet()) {
				if(m.get(k) instanceof Date) {
					m.put(k, sdf.format((Date)m.get(k)));
				}
			}
		}
		return R.ok().put("data", result);
	}

	/**
	 * （按值统计）
	 */
	@IgnoreAuth
	@RequestMapping("/value/{tableName}/{xColumnName}/{yColumnName}")
	public R value(@PathVariable("tableName") String tableName,
				   @PathVariable("yColumnName") String yColumnName,
				   @PathVariable("xColumnName") String xColumnName) {
		Map<String, Object> params = new HashMap<>();
		params.put("table", tableName);
		params.put("xColumn", xColumnName);
		params.put("yColumn", yColumnName);
		List<Map<String, Object>> result = commonService.selectValue(params);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		for(Map<String, Object> m : result) {
			for(String k : m.keySet()) {
				if(m.get(k) instanceof Date) {
					m.put(k, sdf.format((Date)m.get(k)));
				}
			}
		}
		return R.ok().put("data", result);
	}

	/**
	 * （按值统计）时间统计类型
	 */
	@IgnoreAuth
	@RequestMapping("/value/{tableName}/{xColumnName}/{yColumnName}/{timeStatType}")
	public R valueDay(@PathVariable("tableName") String tableName,
					  @PathVariable("yColumnName") String yColumnName,
					  @PathVariable("xColumnName") String xColumnName,
					  @PathVariable("timeStatType") String timeStatType) {
		Map<String, Object> params = new HashMap<>();
		params.put("table", tableName);
		params.put("xColumn", xColumnName);
		params.put("yColumn", yColumnName);
		params.put("timeStatType", timeStatType);
		List<Map<String, Object>> result = commonService.selectTimeStatValue(params);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		for(Map<String, Object> m : result) {
			for(String k : m.keySet()) {
				if(m.get(k) instanceof Date) {
					m.put(k, sdf.format((Date)m.get(k)));
				}
			}
		}
		return R.ok().put("data", result);
	}

	/**
	 * 人脸比对
	 */
	@RequestMapping("/matchFace")
	@IgnoreAuth
	public R matchFace(String face1, String face2, HttpServletRequest request) {
		if(client == null) {
			String APIKey = configService.getOne(new QueryWrapper<ConfigEntity>()
							.eq("name", "APIKey"))
					.getValue();
			String SecretKey = configService.getOne(new QueryWrapper<ConfigEntity>()
							.eq("name", "SecretKey"))
					.getValue();
			String token = BaiduUtil.getAuth(APIKey, SecretKey);
			if(token == null) {
				return R.error("请在配置管理中正确配置APIKey和SecretKey");
			}
			client = new AipFace(null, APIKey, SecretKey);
			client.setConnectionTimeoutInMillis(2000);
			client.setSocketTimeoutInMillis(60000);
		}

		JSONObject res = null;
		try {
			File path = new File(ResourceUtils.getURL("classpath:static").getPath());
			if(!path.exists()) {
				path = new File("");
			}
			File upload = new File(path.getAbsolutePath(), "/upload/");
			File file1 = new File(upload.getAbsolutePath() + "/" + face1);
			File file2 = new File(upload.getAbsolutePath() + "/" + face2);
			String img1 = java.util.Base64.getEncoder().encodeToString(FileUtil.FileToByte(file1));
			String img2 = java.util.Base64.getEncoder().encodeToString(FileUtil.FileToByte(file2));
			MatchRequest req1 = new MatchRequest(img1, "BASE64");
			MatchRequest req2 = new MatchRequest(img2, "BASE64");
			ArrayList<MatchRequest> requests = new ArrayList<>();
			requests.add(req1);
			requests.add(req2);
			res = client.match(requests);
			System.out.println(res.get("result"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return R.error("文件不存在");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return R.ok().put("score", com.alibaba.fastjson.JSONObject.parse(res.getJSONObject("result").get("score").toString()));
	}
}